package collector

import (
	"sort"
	"time"

	"sysinfo/internal/types"

	process "github.com/shirou/gopsutil/v3/process"
)

// CollectActivity 收集最近活动（最近启动的进程、最近访问的文件）
func CollectActivity() (*types.ActivityData, error) {
	recentProcs, _ := collectRecentProcesses(20)
	recentFiles, _ := collectRecentFiles(20)
	return &types.ActivityData{
		RecentProcesses: recentProcs,
		RecentFiles:     recentFiles,
	}, nil
}

// collectRecentProcesses 返回按创建时间倒序的最近进程
func collectRecentProcesses(limit int) ([]types.RecentProcess, error) {
	procs, err := process.Processes()
	if err != nil {
		return nil, err
	}

	items := make([]types.RecentProcess, 0, len(procs))
	for _, p := range procs {
		ct, err := p.CreateTime()
		if err != nil || ct == 0 {
			continue
		}
		name, _ := p.Name()
		cmd, _ := p.Cmdline()
		user, _ := p.Username()
		items = append(items, types.RecentProcess{
			PID:        p.Pid,
			Name:       name,
			Username:   user,
			CreateTime: ct,
			Cmdline:    cmd,
		})
	}

	sort.Slice(items, func(i, j int) bool { return items[i].CreateTime > items[j].CreateTime })
	if limit > 0 && len(items) > limit {
		items = items[:limit]
	}
	return items, nil
}

//// collectRecentFiles 由各平台实现，默认返回空
//func collectRecentFiles(limit int) ([]types.RecentFile, error) {
//	return []types.RecentFile{}, nil
//}

// helper 将毫秒时间戳转为 time.Time（未直接使用，保留以备格式化场景）
func fromMillis(ms int64) time.Time {
	return time.UnixMilli(ms)
}
